package org.gary.news.action;

import static lengreen.util.constant.Constant.DateFomaterString.YYYY_MM_DD_HH_MM_SS;
import static org.gary.core.util.Utils.*;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.gary.base.model.Category;
import org.gary.base.model.Image;
import org.gary.base.service.CategoryService;
import org.gary.base.service.ImageService;
import org.gary.base.service.XxxImageService;
import org.gary.core.service.InitService;
import org.gary.core.util.Util;
import org.gary.core.util.Utils;
import org.gary.news.model.News;
import org.gary.news.service.NewsService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.opensymphony.xwork2.ActionSupport;

/**
 * News 新闻Action
 * @author Gary, lengreen
 * 
 */
@Component
@Scope("prototype")
public class NewsAction extends ActionSupport implements ServletRequestAware,
		ServletResponseAware, SessionAware {
	private static final long serialVersionUID = 3069680747218946087L;
	private HttpServletRequest request;
	private HttpServletResponse response;
	private Map<String, Object> session;
	private InitService initService;

	@Resource
	public void setInitService(InitService initService) {
		this.initService = initService;
	}

	private NewsService newsService;
	private ImageService imageService;
	private CategoryService categoryService;
	private XxxImageService xxxImageService;

	/** 记录单个产品信息 */
	private News news;
	/** 记录产品列表信息 */
	private List<News> newsList;
	/** 记录当前页 */
	private int start;
	/** 记录分页最大记录条数 */
	private int limit;
	/** 通过新闻标题搜索 */
	private String newsTitle;
	/**开始时间*/
	private String fromDate;
	/**结束时间*/
	private String toDate;
	/**新闻类别*/
	private String category;

	/** 记录新闻每页最大条数 */
	private final int MAXNEWS = 9;

	/** 用于规定上传文件的大小 **/
	private static final int BUFFER_SIZE = 200 * 1024;
	private File[] newsImage;
	/** 用String数组来封装多个上传文件名 **/
	private String[] newsImageFileName;
	/** 用String数组来封装多个上传文件类型 **/
	private String[] newsImageContentType;
	/**删除模式*/
	private String mode;
	/**删除谁*/
	private String who;
	/**是否可见*/
	private String visible;
	/**语言*/
	private String lang;
	private String result;

	/**
	 * 增加
	 * @throws Exception
	 */
	public void add() throws Exception {
		try {
			if (news != null) {
				Set<Image> images = Utils.handleImagesUpload(newsImage,
						newsImageFileName, "NewsImage", BUFFER_SIZE);
				Category c = categoryService.loadCategoryByName(getCategory(), news.getLang());
				news.setImages(images);
				news.setCategory(c);
				newsService.save(news);
				initService.newsMinArticle(session);
				result = "{'success':'true'}";
			} else {
				result = "{'success':'false'}";
			}
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 列表
	 * @throws Exception
	 */
	public void list() throws Exception {
		start = parseIndex(start, limit);
		Map<String, Object> where = new HashMap<String, Object>();
		where.put(" entity.visible = ", new Boolean(visible));
		setNewsList(newsService.list(News.class, start, limit, where,
				new Object[] { " entity.id desc " }));

		for (News n : newsList) {
			System.out.println(n);
		}

		JsonConfig config = makeDateFormateJsonConfig(YYYY_MM_DD_HH_MM_SS);
		config.setExcludes(new String[] { "images", "content", "visible" });
		JSONArray newsListJsonArray = JSONArray.fromObject(newsList, config);
		JSONObject newsJsonObject = new JSONObject();
		newsJsonObject.put("newsTotal", newsService.selectTotalCount(null));
		newsJsonObject.put("newsList", newsListJsonArray);
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(newsJsonObject.toString());
	}

	/**
	 * 搜索
	 * @throws Exception
	 */
	public void search() throws Exception {
		start = parseIndex(start, limit);
		Map<String, Object> where = new HashMap<String, Object>();
		where.put(" entity.visible = ", new Boolean(visible));
		setCategory(new String(getCategory().getBytes("iso8859-1"), "utf-8"));

		System.out.println("newsName-->" + newsTitle);
		System.out.println("fromDate-->" + getFromDate());
		System.out.println("toDate-->" + getToDate());
		System.out.println("category-->" + getCategory());

		if (!"".equals(newsTitle.trim())) {
			where.put(" entity.title like ", newsTitle);
		}
		if (!"".equals(getFromDate().trim())) {
			if ("".equals(getToDate().trim())) {
				where.put(" entity.createDate between ", getFromDate()
						+ " 00:00:00' and '"
						+ Utils.getFormatDate(new Date(), YYYY_MM_DD_HH_MM_SS));
			} else {
				where.put(" entity.createDate between ", getFromDate()
						+ " 00:00:00' and '" + getToDate() + " 23:59:59");
			}
		}
		if (!"".equals(category.trim())) {
			where.put(" entity.category.name = ", "'" + category + "'");
		}
		if (!"".equals(lang.trim())) {
			where.put(" entity.lang = ", lang);
		}

		setNewsList(newsService.list(News.class, getStart(), getLimit(), where,
				new Object[] { " entity.id desc " }));

		JsonConfig config = makeDateFormateJsonConfig(YYYY_MM_DD_HH_MM_SS);
		config.setExcludes(new String[] { "images", "content", "visible" });
		JSONArray newsListJsonArray = JSONArray.fromObject(newsList, config);
		JSONObject newsJsonObject = new JSONObject();
		newsJsonObject.put("newsTotal", newsService.selectTotalCount(null));
		newsJsonObject.put("newsList", newsListJsonArray);
		System.out.println("newsJsonObject-->" + newsJsonObject.toString());
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(newsJsonObject.toString());
	}

	/**
	 * 加载
	 * @throws IOException
	 */
	public void load() throws IOException {
		News p = newsService.load(News.class, news.getId());
		JsonConfig config = makeDateFormateJsonConfig(YYYY_MM_DD_HH_MM_SS);
		config.setExcludes(new String[] { "category.parent",
				"category.children", "images" });
		JSONObject newsJsonObject = JSONObject.fromObject(p, config);
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(newsJsonObject.toString());
	}

	/**
	 * 加载关联的images
	 * @throws IOException
	 */
	public void loadImages() throws IOException {
		JsonConfig config = makeDateFormateJsonConfig(YYYY_MM_DD_HH_MM_SS);
		config.setExcludes(new String[] { "createDate", "id", "visible" });
		JSONArray imagesJsonArray = JSONArray.fromObject(newsService
				.loadImages(news.getId()), config);
		JSONObject imagesJsonObject = new JSONObject();
		imagesJsonObject.put("images", imagesJsonArray);
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(imagesJsonObject.toString());
	}

	/**
	 * 更新
	 * @throws IOException
	 */
	public void update() throws IOException {
		if (news != null) {
			Set<Image> images = handleImagesUpload(newsImage,
					newsImageFileName, "NewsImage", BUFFER_SIZE);
			if (images == null) {
				images = new HashSet<Image>();
			}
			for (Image i : newsService.loadImages(news.getId())) {
				images.add(i);
			}
			news.setImages(images);

			Category c = categoryService.loadCategoryByName(category, news.getLang());
			news.setCategory(c);
			newsService.update(news);
			initService.newsMinArticle(session);
			result = "{'success':'true'}";
		} else {
			result = "{'success':'false'}";
		}
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(result);
	}

	/**
	 * 删除
	 * @throws IOException
	 */
	public void delete() throws IOException {
		try {
			if ("delete".equals(getMode())) {
				Object[] imageIds = getXxxImageService().deleteByXxxId(
						getWho(), news.getId());
				if (imageIds.length > 0) {
					getImageService().delete(Image.class, imageIds);
				}
				newsService.delete(news);
				initService.newsMinArticle(session);
				result = "{'result':'delete'}";
			} else if ("update".equals(getMode())) {
				newsService.update(News.class, new Object[] { news.getId() }, false);
				initService.newsMinArticle(session);
				result = "{'result':'update'}";
			} else {
				result = "{'result':'none'}";
			}
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 回收
	 * @throws IOException
	 */
	public void recover() throws IOException {
		try {
			if (news != null) {
				News e = newsService.load(News.class, news.getId());
				if(e.getCategory().isVisible()) {
					newsService.update(News.class, new Object[] { news
						.getId() }, true);
					result = "{'success':'true', 'msg':'recover'}";
				} else {
					result = "{'success':'false', 'msg':'categoryUnvisible'}";
				}
			} else {
				result = "{'success':'false', 'msg':'null'}";
			}
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Resource
	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	@Resource
	public void setNewsService(NewsService newsService) {
		this.newsService = newsService;
	}

	/**
	 * 显示基本初始信息
	 * @return
	 * @throws Exception
	 * @author Gary
	 */
	public String minMesg() throws Exception {
		int newsCurrentPage;
		int cId;
		List<News> news = null;
		String newsPage = request.getParameter("newsPage");
		String categoryId = request.getParameter("categoryId");
		if (newsPage != null) {
			newsCurrentPage = Integer.parseInt(newsPage);
		} else {
			newsCurrentPage = 0;
		}

		// 得到分页bean
		Util u = new Util("news", MAXNEWS, session.get("WW_TRANS_I18N_LOCALE"));

		/** 如果类型ID!=null则查询类型新闻 */
		if (categoryId != null) {			
			cId = Integer.parseInt(categoryId);
			if(cId!=0){
				if(!newsService.getParentId(cId)){
					news=newsService.list(News.class, MAXNEWS, newsCurrentPage, session.get("WW_TRANS_I18N_LOCALE"), newsService.getId(cId));
				}else{
					news=newsService.list(News.class, MAXNEWS, newsCurrentPage, session.get("WW_TRANS_I18N_LOCALE"), cId);
				}			
				u = new Util("news", MAXNEWS, cId,session.get("WW_TRANS_I18N_LOCALE"));
			}else{
				Map<String, Object> where = new HashMap<String, Object>();
				where.put("entity.lang =", session.get("WW_TRANS_I18N_LOCALE")
						.toString());
				news = newsService.getNews(where, newsCurrentPage, MAXNEWS,
						new Object[] { " entity.id desc " });
			}
		} else {
			Map<String, Object> where = new HashMap<String, Object>();
			where.put("entity.lang =", session.get("WW_TRANS_I18N_LOCALE")
					.toString());
			news = newsService.getNews(where, newsCurrentPage, MAXNEWS,
					new Object[] { " entity.id desc " });
		}

		// 设置当前页面
		u.setYe(newsCurrentPage);

		/** 把分页、新闻放入request */
		request.setAttribute("fenye", u);
		request.setAttribute("news", news);
		initService.initAll(session);
		return SUCCESS;

	}

	/**
	 * 显示新闻内容
	 * 
	 * @return
	 * @author Gary
	 */
	public String showMesg() {
		int nid;
		String newsId = request.getParameter("newsId");
		if (newsId != null) {
			nid = Integer.parseInt(newsId);
			newsService.addBrowse(nid);
			News news = newsService.load(News.class, nid, session
					.get("WW_TRANS_I18N_LOCALE"));
			request.setAttribute("newsbean", news);
			initService.initAll(session);
			return SUCCESS;
		} else {
			session.put("error", "新闻显示失败，参数错误！");
			return ERROR;
		}
	}

	public String searchNews() {
		initService.initAll(session);
		Map<String, Object> where = new HashMap<String, Object>();
		where.put(" entity.visible = ", new Boolean(true));
		String newsFun = request.getParameter("newsFun");
		if (newsFun != null) {
			String newsWhat = request.getParameter("newsWhat").trim();
			if ("date".equals(newsFun)) {
				where.put("entity.createDate like ", newsWhat);
			} else if ("type".equals(newsFun)) {
				Category cate = categoryService.load(Category.class, newsWhat,
						session.get("WW_TRANS_I18N_LOCALE"));
				if (cate != null) {
					where.put("entity.category.id = ", cate.getId());
				}
			} else if ("name".equals(newsFun)) {
				where.put("entity.title like ", newsWhat);
			}
			where.put("entity.lang = ", session.get("WW_TRANS_I18N_LOCALE")
					.toString());
			List<News> news = newsService.list(News.class, 0, MAXNEWS, where,
					new Object[] { " entity.id desc " });
			request.setAttribute("news", news);
			return SUCCESS;
		} else {
			session.put("error", "新闻显示失败，参数错误！");
			return ERROR;
		}
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		this.request = arg0;
	}

	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		this.response = arg0;
	}

	public void setNews(News news) {
		this.news = news;
	}

	public News getNews() {
		return news;
	}

	public void setNewsList(List<News> newsList) {
		this.newsList = newsList;
	}

	public List<News> getNewsList() {
		return newsList;
	}

	public void setNewsTitle(String newsTitle) {
		this.newsTitle = newsTitle;
	}

	public String getNewsTitle() {
		return newsTitle;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public String getCategory() {
		return category;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getStart() {
		return start;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getLimit() {
		return limit;
	}

	public void setFromDate(String fromDate) {
		this.fromDate = fromDate;
	}

	public String getFromDate() {
		return fromDate;
	}

	public void setToDate(String toDate) {
		this.toDate = toDate;
	}

	public String getToDate() {
		return toDate;
	}

	public void setNewsImageFileName(String[] newsImageFileName) {
		this.newsImageFileName = newsImageFileName;
	}

	public String[] getNewsImageFileName() {
		return newsImageFileName;
	}

	public void setNewsImageContentType(String[] newsImageContentType) {
		this.newsImageContentType = newsImageContentType;
	}

	public String[] getNewsImageContentType() {
		return newsImageContentType;
	}

	public void setNewsImage(File[] newsImage) {
		this.newsImage = newsImage;
	}

	public File[] getNewsImage() {
		return newsImage;
	}

	public void setLang(String lang) {
		this.lang = lang;
	}

	public String getLang() {
		return lang;
	}

	public void setVisible(String visible) {
		this.visible = visible;
	}

	public String getVisible() {
		return visible;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	public String getMode() {
		return mode;
	}

	public void setWho(String who) {
		this.who = who;
	}

	public String getWho() {
		return who;
	}

	@Resource
	public void setXxxImageService(XxxImageService xxxImageService) {
		this.xxxImageService = xxxImageService;
	}

	public XxxImageService getXxxImageService() {
		return xxxImageService;
	}

	@Resource
	public void setImageService(ImageService imageService) {
		this.imageService = imageService;
	}

	public ImageService getImageService() {
		return imageService;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
}